package cn.xcstudenth.myapplication.webviewutils;

import android.annotation.SuppressLint;
import android.os.Build;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;

import java.lang.ref.WeakReference;

/**
 * Created by 赵航 on 2020/8/13.
 * WeChat: zhao--hang--
 */
public class WebViewUtils {

    //webView加载,只能加载Url,加载缓慢
    @SuppressLint("JavascriptInterface")
    public static void setWebHtml(WebView webView, String content) {
        if (content == null) {
            return;
        }
        WeakReference<WebView> mWebView = new WeakReference<WebView>(webView);

        if (mWebView.get() != null) {
            mWebView.get().setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    return true;
                }
            });
            mWebView.get().getSettings().setJavaScriptEnabled(true);
            mWebView.get().getSettings().setDomStorageEnabled(true);
            mWebView.get().getSettings().setUseWideViewPort(true);
            mWebView.get().getSettings().setLoadWithOverviewMode(true);
            mWebView.get().getSettings().setAllowUniversalAccessFromFileURLs(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                mWebView.get().getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
            mWebView.get().getSettings().setBlockNetworkImage(false);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                mWebView.get().getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
            } else {
                mWebView.get().getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
            }
            //加载网址
            //mWebView.get().loadUrl(content);
            mWebView.get().loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);
            //设置点击事件
            mWebView.get().addJavascriptInterface(new MJavascriptInterface(), "imagelistener");
            mWebView.get().setWebViewClient(new MyWebViewClient());
        }
    }
}
